/**
 * 
 */
package com.neal.web.controller;

import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import com.neal.domain.securities.User;
import com.neal.web.validation.UserValidator;


/**
 * @author Neal
 * @version 1.0
 * @description 
 */
@Controller
@RequestMapping("/user")
@SessionAttributes("user")
public class UserController {
	
	@Autowired
	private MessageSource messageSource;
	
	@Value("#{messageSource.getMessage('admin.email',null,null)}")
	private String email;
	
	@InitBinder
	private void initBinder(ServletRequestDataBinder binder){
		binder.replaceValidators(new UserValidator());
	}
	
	
	@ModelAttribute("users")
	public List<User> allUser(){
		System.out.println("@ModelAttribute Begin!");
		List<User> users = new ArrayList<User>();
		User u1 = new User(); u1.setUserId("1");u1.setUserName("u1");
		User u2 = new User(); u2.setUserId("2");u2.setUserName("u2");
		User u3 = new User(); u3.setUserId("3");u3.setUserName("u3");
		users.add(u1);users.add(u2);users.add(u3);
		return users;
		
	}
	
	@RequestMapping(value="getUser/{userId}",method=RequestMethod.GET)
	public String do1(@PathVariable String userId,Model model){
		User u1 = new User(); u1.setUserId(userId);u1.setUserName("uuid");
		model.addAttribute("user", u1);
		model.addAttribute("email",email);
		return "user";
	}
	
	@RequestMapping(value="setUserAndRole",method=RequestMethod.POST)
	public String do2(@Valid @ModelAttribute User user2,BindingResult result,Model model , SessionStatus status) {
		model.addAttribute("email",email);
		return "user";
	}
	
	@RequestMapping(value="setUserAndRole2",method=RequestMethod.POST)
	public String do3(@Valid @ModelAttribute User user,BindingResult result,SessionStatus status) {
		System.out.println(user.getUserId() + "  " + user.getUserName()+"  " + user.getRole().getId());
		status.setComplete();
		return "user";
	}
	
	@RequestMapping("testBind")
	public String do4(@ModelAttribute User user,BindingResult result,Model model){
		return "user";
	}
	
}
